package downloads

import (
	"os"
	"container/list"
	"./transfers"
)

const (
	MAX_RETRIES  = 10
)

func Download(url string, targetFile string, maxRetries int) (err error) {
	var transfer transfers.Transfer
	transfer = transfers.NewHttpTransfer(transfers.Resource{url})
	totalSize, err := transfer.TotalSize()
	println(totalSize)

	blockSize := 1024
	startPos := 0
	var chans = list.New()
	for {
		if startPos >= totalSize - 1 {
			break
		}

		c := make(chan []byte)
		chans.PushBack(c)
		l := blockSize
		if startPos + l > totalSize {
			l = totalSize
		}
		go transfer.PartDownload(startPos,  l, c)

		startPos += l
	}

	f, err := os.OpenFile(targetFile, os.O_CREATE | os.O_RDWR, 0666)
	defer f.Close()

	var i int = 0
	for e := chans.Front(); e != nil; e = e.Next() {
		c, _ := e.Value.(chan []byte)
		buffer, ok := <- c
		if ok {
			if err != nil { panic(err) }
			//stat, err := f.Stat()
			//f.Seek(int64(blockSize * i), 0)
			if err != nil { panic(err) }

			//buffer, _ := ioutil.ReadAll(body)
			written, err := f.WriteAt(buffer, int64(blockSize * i))
			//written, err := io.Copy(f, body)
			if err != nil { panic(err) }
			println("written: ", written)
		}

		i++
	}


	return
}